﻿$(function () {
    var manageLogin = function () {
        if ($(".login-button").html() == "登　录") {
            var username = $("#txt-username").val(),
                password = $("#txt-password").val();
            if (ruleUserName(username)) {
                if (rulePassWord(password)) {
                    ajaxLogin(username, password);
                }
            }
        }
    };

    var ruleUserName = function (username) {
        if (!/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/i.test(username)) {
            alert("用户名不合法，字母开头，允许4-16字节，允许字母数字下划线");
            return false;
        }
        return true;
    };

    var rulePassWord = function (password) {
        if (password.length < 6 || password.length > 16) {
            alert("密码长度在6-16字节之间");
            return false;
        }
        return true;
    };

    var ajaxLogin = function (username, password) {
        $.ajax({
            url: "/work/authorize/dologin",
            type: "post", dataType: "json",
            data: {
                username: username,
                password: password
            },
            beforeSend: function () {
                $(".login-button").html("请稍后...");
                $("#txt-username").attr("readonly", "readonly");
                $("#txt-password").attr("readonly", "readonly");
            },
            complete: function () {
                $(".login-button").html("登　录");
                $("#txt-username").removeAttr("readonly");
                $("#txt-password").removeAttr("readonly");
            },
            success: function (result) {
                if (result.success) {
                    $(".login-button").html("登录成功");
                    location.replace("/work/home/index");
                }
                else { alert(result.message); }
            },
            error: function (r, s, t) {
                alert("系统错误，请稍后重试");
                console.error(r); console.error(s);
            }
        });
    };

    $("#txt-username").keyup(function (e) {
        if (e.keyCode == 13) {
            $("#txt-password").focus();
        }
    });

    $("#txt-password").keyup(function (e) {
        if (e.keyCode == 13) { manageLogin(); }
    });

    $(".login-button").click(function () {
        manageLogin();
    });

    $("#txt-username").focus();
});